package com.riku.security.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.riku.security.common.SeCommonResponse;
import com.riku.security.common.SeSecurityFailException;
import com.riku.security.model.SeApiRole;
import com.riku.security.model.SeMenu;
import com.riku.security.service.SeCommonService;
import com.riku.security.service.SeMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 1 on 2021/5/24.
 */
@Configuration
@WebFilter(filterName = "z-security-filter")
@ConditionalOnBean({SeAuthorityService.class,SeExternalUserService.class})
public class SeAuthorityFilter implements Filter {

    @Autowired
    private SeAuthorityService seAuthorityService;
    @Autowired
    private SeCommonService seCommonService;

    // <String,<url>>
    public static Map<String,List<SeApiRole>> rootPaths;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        rootPaths = new HashMap<>();

        // buildServicePath
        String[] services = seAuthorityService.buildServicePath();
        for (String serviceCode : services) {
            rootPaths.put(serviceCode,seCommonService.getApiAndRole(serviceCode));
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String uri = ((HttpServletRequest)servletRequest).getRequestURI();

        boolean checked = checkPath(uri);
        if (!checked) {
            // 如果是调用权限系统的接口被鉴权,则返回统一对象给权限系统前端弹窗,引入系统的接口鉴权失败就抛出SeSecurityFailException,自行处理返回
            if (uri.startsWith("/se/")) {
                SeCommonResponse seCommonResponse = SeCommonResponse.fail("权限不足");
                servletResponse.setContentType("application/json; charset=utf-8");
                servletResponse.setCharacterEncoding("UTF-8");

                ObjectMapper objectMapper = new ObjectMapper();
                String userJson = objectMapper.writeValueAsString(seCommonResponse);
                OutputStream out = servletResponse.getOutputStream();
                out.write(userJson.getBytes("UTF-8"));
                out.flush();
                return;
            } else {
                throw new SeSecurityFailException();
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }

    private boolean checkPath(String path) {
        for (String w :  seAuthorityService.buildWhiteList()) {
            if (path.startsWith(w)) {
                return true;
            }
        }

        String currentServiceCode = seAuthorityService.getCurrentServiceCode();

        SeApiRole apiRole = null;
        if (currentServiceCode != null && !"".equals(currentServiceCode)) {
            // 若提供了当前接口所属serviceCode
            List<SeApiRole> apiList = rootPaths.get(currentServiceCode);

            for (SeApiRole api : apiList) {
                if (api.getPath().startsWith(path)) {
                    apiRole = api;
                    break;
                }
            }
        } else {
            // 若未提供当前serviceCode，
            for (List<SeApiRole> apiList : rootPaths.values()) {
                for (SeApiRole api : apiList) {
                    if (api.getPath().startsWith(path)) {
                        apiRole = api;
                        break;
                    }
                }
            }
        }

        //不在拦截列表中，放过
        if (apiRole == null) {
            return true;
        }

        // 获取用户权限列表
        List<Long> userRoles = seAuthorityService.getPathsFromCache();

        if (apiRole.getRoleIds() != null && !Collections.disjoint(apiRole.getRoleIds(),userRoles)) {
            return true;
        }

        return false;
    }

    public static Map<String,List<SeApiRole>> getRootPaths() {
        return rootPaths;
    }
}
